package com.rankeiot.core.util.castor;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 数据类型转换器
 * @param <T>
 */
public interface Castor<T> {
    String STRING_NULL="null";
    String STRING_UNDEFINED="undefined";
    String STRING_INFINITY="Infinity";
    /**
     * 类型转换
     * @param v
     * @return
     */
    T cast(Object v);

    /**
     * 注册类型转换器
     * @param type
     * @param castor
     * @param <T>
     */
    static<T> void register(Class<T> type, Castor<T> castor){
        Casters.register(type,castor);
    }

    /**
     * 把数据转换到指定类型
     * @param obj
     * @param type
     * @param <T>
     * @return
     */
    static <T> T castTo(Object obj, Class<T> type){
        if(type.isInstance(obj)){
            return (T)obj;
        }
        return Casters.castTo(obj,type);
    }

    /**
     * 获取对应类型的转换器
     * @param type
     * @param <T>
     * @return
     */
    static <T> Castor<T> getCastor(Class<T> type){
        return Casters.getCastor(type);
    }
}

class Casters{
    private static Map<Class, Castor> castorMap=new HashMap<>();
    static<T> void register(Class<T> type, Castor<T> castor){
        castorMap.put(type,castor);
    }
    static<T> T castTo(Object obj, Class<T> type){
        Castor<T> c=getCastor(type);
        if(c!=null){
            return c.cast(obj);
        }
        return null;
    }
    static <T> Castor<T> getCastor(Class<T> type){
        return castorMap.get(type);
    }
    static {
        register(Boolean.TYPE, BooleanCastor.instance);
        register(Boolean.class, BooleanCastor.instance);
        register(Date.class,DateCastor.instance);
        register(Double.class,DoubleCastor.instance);
        register(Double.TYPE,DoubleCastor.instance);
        register(Integer.TYPE,IntCastor.instance);
        register(Integer.class,IntCastor.instance);
        register(Long.TYPE,LongCastor.instance);
        register(Long.class,LongCastor.instance);
        register(Float.TYPE,FloatCastor.instance);
        register(Float.class,FloatCastor.instance);
        register(String.class, StringCastor.instance);
        register(BigDecimal.class,BigDecimalCastor.instance);
        register(Map.class,MapCastor.instance);
        register(List.class,ListCastor.instance);
        register(Character.class,CharacterCastor.instance);
        register(Character.TYPE,CharacterCastor.instance);
    }
}
